package com.zhihu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    //创建token
    public String SignToken(String s){
        //1.设置签名算法
        Algorithm algorithm = Algorithm.HMAC256("secret");
        //2.设置头部信息
        Map header = new HashMap();
        header.put("typ","JWT");
        header.put("alg","HS256");
        //3.创建token
        String token = JWT.create()
                //1.设置头部
                .withHeader(header)
                //2.设置载荷
                .withIssuer("auth0")
                .withIssuedAt(new Date())
                .withClaim("user",s)
                //3.设置签名
                .sign(algorithm);

        return token;
    }

    //解析token
    public String VerifyToekn(String token){
        Algorithm algorithm = Algorithm.HMAC256("secret");
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("auth0")
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        //从jwt中获取到用户的信息
        String user = jwt.getClaim("user").asString();

        return user;
    }

}
